package edu.umn.msse.farside.FourH.web;

import com.dreamlizard.miles.beans.TimestampPropertyEditor;
import edu.umn.msse.farside.FourH.domain.Event;
import edu.umn.msse.farside.FourH.domain.Volunteer;
import edu.umn.msse.farside.FourH.services.EventService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.sql.Timestamp;

/**
 * Created by IntelliJ IDEA.
 * User: corcutt
 * Date: Mar 19, 2009
 * Time: 8:17:55 PM
 * To change this template use File | Settings | File Templates.
 */
@Controller
@RequestMapping("/editEvent")
public class EditEventController
{
    private EventService eventService;

    @Autowired
    public void setEventService(EventService eventService) {
        this.eventService = eventService;
    }

    @InitBinder
    public void setAllowedFields(WebDataBinder dataBinder) {
        dataBinder.registerCustomEditor(Timestamp.class, new TimestampPropertyEditor());
    }


    @RequestMapping(method = RequestMethod.GET)
    public String editEventForm(@RequestParam(required=true) Long eventID, Model model, HttpSession session, HttpServletRequest request) {
        // event id comes in on the request as a hidden parameter
        Volunteer volunteer = (Volunteer)session.getAttribute("volunteer");
        Event event = eventService.getEvent(eventID);
        if (event.getAdministrator().getId().equals(volunteer.getId()))
        {
            model.addAttribute("event", event);
            request.setAttribute("event", event);
            //request.setAttribute("allPositions", eventService.listAllPositions(event));

            return "editEvent";
        }
        else
        { // not the administrator .. someone is trying to sneak in .. redirect
            return "redirect:futureEvents";
        }
    }

    @RequestMapping(method = RequestMethod.POST)
    public String editEventForm(@ModelAttribute(value = "event") Event event, BindingResult result, Model model, HttpSession session)
    {
        // any validation checking
        new EventValidator().validate(event, result);

        Event eventToUpdate = eventService.getEvent(event.getId());

        if (result.hasErrors())
        {
            event.setEventPositions(eventToUpdate.getEventPositions());
            return "editEvent";
        }
        else
        {
            eventToUpdate = eventToUpdate.updateEvent(event);
            Event updatedEvent = eventService.updateEvent(eventToUpdate);
            model.addAttribute("event", updatedEvent);

            return "redirect:myEvents";
        }
    }


}
